class Solution(object): def solve(self, board): """ :type board: List[List[str]] :rtype: void Do not return anything, modify board in-place instead. """ if not board or not board[0]: return n = len(board) m = len(board[0]) queue = [] # 保存所有位于边缘的O for i in range(n): for j in range(m): if ((i in (0, n - 1)) or (j in (0, m - 1))) and board[i][j] == 'O': # i in (0, n - 1) 最上面和最下面两排 queue.append((i, j)) print (i,j) # 保存所有与边缘O相连的O while queue: r, c = queue.pop(0) # i, j = r, c if 0 <= r < n and 0 <= c < m and board[r][c] == 'O': board[r][c] = 'M' # 变为M的则是不需要变成X的 if r - 1 >= 0 and board[r - 1][c] == 'O': queue.append((r - 1, c)) if r + 1 < n and board[r + 1][c] == 'O': queue.append((r + 1, c)) if c - 1 >= 0 and board[r][c - 1] == 'O': queue.append((r, c - 1)) if c + 1 < m and board[r][c + 1] == 'O': queue.append((r, c + 1)) # 重新更新棋盘 for i in range(n): for j in range(m): if board[i][j] == 'M': board[i][j] = 'O' else: board[i][j] = 'X'